import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

import {
  ValidVersion,
  GetWxSessionKey,
  GssGetUserMobileInfo,
  Login,
  Reg,
  GetCustomerAccountCode,
  GetCustomerOrder,
  GetCustomerIntegralList,
  CustomerGetChilds,
  SwichAccount,
  UpdateCustomerInfo,
  GetMyCoupon,
  GiveCoupon,
  GetCustomerAllOptometry,
  GetCustomerAllOptometryLineData,
  GetCustomerAllOrder,
  GetCountCardList,
  GetUserInfo,
  GetRecommendList,
} from '../api/api.js';
import { useAppointmentStore } from '@/store/appointment';

const KEY_USER_INFO = 'userInfo';

export const useUserStore = defineStore('user', () => {
  const needRegister = ref(false);
  const mobile = ref();
  const openId = ref();
  const sessionKey = ref();
  const userInfoObj = uni.getStorageSync(KEY_USER_INFO) || {};
  console.warn('userInfoObj', userInfoObj);
  const userInfo = ref(userInfoObj);
  const isLogin = computed(() => Boolean(userInfo.value.token));
  const accountCode = ref('');
  const customerOrderPage = ref(1);
  const customerOrders = ref([]);
  const customerOrderTotal = ref(-1);
  const customerIntegralPage = ref(1);
  const customerIntegrals = ref([]);
  const customerIntegralTotal = ref(-1);
  const customerChilds = ref([]);
  const coupons = ref([]);
  const selectCustomerForOptometry = ref(userInfoObj.customerId);
  const customerAllOptometry = ref([]);
  const optometryLineData = ref([]);
  const allOrders = ref([]);
  const countCardList = ref([]);
  const recommandList = ref([]);
  const referrer = ref(''); // 推荐人

  function validVersion() {
    ValidVersion();
  }
  function getWxSessionKey() {
    uni.login({
      provider: 'weixin',
      success: (result) => {
        console.log('weixin login success', result);
        const { code } = result;
        GetWxSessionKey(code).then((data) => {
          openId.value = data.openId;
          sessionKey.value = data.sessionKey;
        });
      },
      fail: () => {
        uni.showToast({
          title: '登录失败',
          icon: 'none',
        });
      },
    });
  }
  const gssGetUserMobileInfo = async (Code) => {
    const appId = uni.getAccountInfoSync().miniProgram.appId;
    console.warn('appId', appId);
    return await GssGetUserMobileInfo(appId, Code);
  };
  async function register(
    Mobile,
    Name,
    Addr,
    Birthday,
    Sex,
    HeadPortrait,
    ReadMe,
    ParentId,
  ) {
    uni.showLoading({
      title: '注册中...',
    });
    const appId = uni.getAccountInfoSync().miniProgram.appId;
    try {
      const data = await Reg(
        appId,
        Mobile,
        Name,
        Addr,
        Birthday,
        Sex,
        HeadPortrait,
        ReadMe,
        '', // WxOpenId
        ParentId,
        referrer.value,
      );
      userInfo.value = data;
      selectCustomerForOptometry.value = data.customerId;
      uni.setStorageSync(KEY_USER_INFO, data);
      return Boolean(data.token);
    } catch (error) {
      console.error('register error', error);
      return false;
    } finally {
      uni.hideLoading();
    }
  }
  async function login(Code) {
    const appId = uni.getAccountInfoSync().miniProgram.appId;
    const { phoneNumber, countryCode } = await gssGetUserMobileInfo(Code);
    mobile.value = phoneNumber;
    // mobile.value = '15989193498';
    try {
      const data = await Login(appId, phoneNumber);
      // const data = await Login(appId, '15989193498');
      userInfo.value = data;
      selectCustomerForOptometry.value = data.customerId;
      uni.setStorageSync(KEY_USER_INFO, data);
      return Boolean(data.token);
    } catch (error) {
      console.error('login error', error);
      if (error.includes('注册')) {
        needRegister.value = true;
      }
      return false;
    }
  }
  async function loginByMobile(Mobile, SmsCode) {
    const appId = uni.getAccountInfoSync().miniProgram.appId;
    try {
      const data = await Login(appId, Mobile, '', '', SmsCode);
      userInfo.value = data;
      selectCustomerForOptometry.value = data.customerId;
      uni.setStorageSync(KEY_USER_INFO, data);
      return Boolean(data.token);
    } catch (error) {
      console.error('login error', error);
      return false;
    }
  }
  async function logout() {
    uni.showModal({
      title: '提示',
      content: '确定退出登录？',
      success: async (res) => {
        if (res.confirm) {
          userInfo.value = {};
          uni.removeStorageSync(KEY_USER_INFO);
          const appointmentStore = useAppointmentStore();
          appointmentStore.historyAppointments = [];
          uni.reLaunch({
            url: '/pages/appointment/appointment',
          });
        }
      },
    });
  }
  async function getCustomerAccountCode() {
    const data = await GetCustomerAccountCode();
    accountCode.value = data.temp1[0].accountCode;
  }
  async function getCustomerOrder(type, clean = false) {
    if (clean) {
      console.warn('clean customerOrders');
      customerOrders.value = [];
      customerOrderTotal.value = -1;
      customerOrderPage.value = 1;
    }
    if (
      customerOrderTotal.value !== -1 &&
      customerOrders.value.length >= customerOrderTotal.value
    ) {
      console.warn('customerOrders has been loaded');
      return;
    }
    uni.showLoading({
      title: '加载中...',
    });
    const data = await GetCustomerOrder(type, customerOrderPage.value);
    // console.log('getCustomerOrder', data);
    customerOrders.value = [...customerOrders.value, ...data.pagingData];
    customerOrderTotal.value = data.total;
    customerOrderPage.value += 1;
    uni.hideLoading();
  }
  async function getCustomerIntegralList(clean = false) {
    if (clean) {
      console.warn('clean customerIntegrals');
      customerIntegrals.value = [];
      customerIntegralTotal.value = -1;
      customerIntegralPage.value = 1;
    }
    if (
      customerIntegralTotal.value !== -1 &&
      customerIntegrals.value.length >= customerIntegralTotal.value
    ) {
      console.warn('customerIntegrals has been loaded');
      return;
    }
    uni.showLoading({
      title: '加载中...',
    });
    const data = await GetCustomerIntegralList(customerIntegralPage.value);
    // console.log('getCustomerIntegralList', data);
    customerIntegrals.value = [...customerIntegrals.value, ...data.pagingData];
    customerIntegralTotal.value = data.total;
    customerIntegralPage.value += 1;
    uni.hideLoading();
  }
  async function getCustomerChilds() {
    uni.showLoading({
      title: '加载中...',
    });
    const data = await CustomerGetChilds();
    customerChilds.value = data.temp1;
    await getCustomerAllOptometry();
    await getCustomerAllOptometryLineData();
    uni.hideLoading();
  }
  async function switchAccount(CustomerId, Mobile) {
    if (!isLogin.value) {
      return;
    }
    const data = await SwichAccount(Mobile, CustomerId);
    console.warn('switchAccount', data);
    userInfo.value = { ...userInfo.value, token: data.token };
    // userInfo.value = data;
    uni.setStorageSync(KEY_USER_INFO, userInfo.value);
    await getUserInfo();
    await getCustomerChilds();
  }
  async function updateCustomerName(name) {
    uni.showLoading({
      title: '正在更新',
    });
    await UpdateCustomerInfo(name, '', userInfo.value.birthday);
    userInfo.value = { ...userInfo.value, customerName: name };
    uni.setStorageSync(KEY_USER_INFO, { ...userInfo.value });
    uni.showToast({
      title: '更新成功',
    });
  }
  async function updateCustomerAddr(addr) {
    await UpdateCustomerInfo('', addr, userInfo.value.birthday);
  }
  async function updateCustomerBirthday(Birthday) {
    uni.showLoading({
      title: '正在更新',
    });
    await UpdateCustomerInfo('', '', Birthday);
    userInfo.value = { ...userInfo.value, birthday: Birthday };
    uni.setStorageSync(KEY_USER_INFO, { ...userInfo.value });
    uni.showToast({
      title: '更新成功',
    });
  }
  async function updateCustomerSex(Sex) {
    uni.showLoading({
      title: '正在更新',
    });
    await UpdateCustomerInfo('', '', userInfo.value.birthday, Sex);
    userInfo.value = { ...userInfo.value, sex: Sex };
    uni.setStorageSync(KEY_USER_INFO, { ...userInfo.value });
    uni.showToast({
      title: '更新成功',
    });
  }
  async function updateHeadPortrait(HeadPortrait) {
    uni.showLoading({
      title: '正在更新',
    });
    try {
      await UpdateCustomerInfo(
        '',
        '',
        userInfo.value.birthday,
        '',
        HeadPortrait,
      );
      await getUserInfo();
      uni.showToast({
        title: '更新成功',
      });
    } catch (e) {
      console.error(e);
      uni.showToast({
        title: '更新失败',
        icon: 'none',
      });
    }
  }
  async function getMyCoupon() {
    uni.showLoading({
      title: '加载中...',
    });
    const data = await GetMyCoupon();
    coupons.value = data.temp1;
    uni.hideLoading();
  }
  async function giveCoupon(CouponNumber) {
    if (isLogin.value) {
      const GiftedCustomerId = userInfo.value.customerId;
      const data = await GiveCoupon(CouponNumber, GiftedCustomerId);
    }
  }
  async function getCustomerAllOptometry() {
    if (!isLogin.value) {
      return;
    }
    const user = customerChilds.value.find(
      (item) => item.customerId === selectCustomerForOptometry.value,
    );
    const { token } = await SwichAccount(user.mobile, user.customerId);
    const data = await GetCustomerAllOptometry(token);
    customerAllOptometry.value = data;
  }
  async function getCustomerAllOptometryLineData() {
    if (!isLogin.value) {
      return;
    }
    const user = customerChilds.value.find(
      (item) => item.customerId === selectCustomerForOptometry.value,
    );
    const { token } = await SwichAccount(user.mobile, user.customerId);
    const data = await GetCustomerAllOptometryLineData(token);
    optometryLineData.value = data.temp1;
  }
  async function setSelectCustomerForOptometry(customerId) {
    selectCustomerForOptometry.value = customerId;
    uni.showLoading({
      title: '加载中...',
    });
    await getCustomerAllOptometry();
    await getCustomerAllOptometryLineData();
    uni.hideLoading();
  }
  async function getCustomerAllOrder() {
    uni.showLoading({
      title: '加载中...',
    });
    const data = await GetCustomerAllOrder();
    allOrders.value = data;
    uni.hideLoading();
  }
  async function getCountCardList() {
    uni.showLoading({
      title: '加载中...',
    });
    const data = await GetCountCardList();
    countCardList.value = data.temp1;
    uni.hideLoading();
  }
  async function getUserInfo() {
    if (isLogin.value) {
      const data = await GetUserInfo();
      const userInfoNew = data.temp1[0] || {};
      userInfo.value = { ...userInfo.value, ...userInfoNew };
      uni.setStorageSync(KEY_USER_INFO, { ...userInfo.value });
    }
  }
  async function getRecommendList() {
    uni.showLoading({
      title: '加载中...',
    });
    const data = await GetRecommendList();
    recommandList.value = data.temp1;
    // recommandList.value = [{}];
    uni.hideLoading();
  }

  function setReferrer(Referrer) {
    referrer.value = Referrer;
  }

  return {
    mobile,
    needRegister,
    openId,
    sessionKey,
    validVersion,
    getWxSessionKey,
    login,
    loginByMobile,
    register,
    logout,
    isLogin,
    userInfo,
    getCustomerAccountCode,
    accountCode,
    getCustomerOrder,
    customerOrders,
    customerOrderTotal,
    getCustomerIntegralList,
    customerIntegrals,
    customerIntegralTotal,
    customerChilds,
    getCustomerChilds,
    switchAccount,
    updateCustomerName,
    updateCustomerAddr,
    updateCustomerBirthday,
    updateCustomerSex,
    updateHeadPortrait,
    coupons,
    getMyCoupon,
    giveCoupon,
    selectCustomerForOptometry,
    setSelectCustomerForOptometry,
    getCustomerAllOptometry,
    customerAllOptometry,
    getCustomerAllOptometryLineData,
    optometryLineData,
    getCustomerAllOrder,
    allOrders,
    getCountCardList,
    countCardList,
    getUserInfo,
    getRecommendList,
    recommandList,
    referrer,
    setReferrer,
  };
});
